<template>
    <div class="login-container">
      <h1>登录</h1>
      <input v-model="user_account" type="text" placeholder="请输入账号">
      <input v-model="password" type="password" placeholder="请输入密码">
      <button class="login-button" @click="login">登录</button>
      <div class="register-link">
        还没有账号? <router-link to="/reg">点此注册</router-link>
      </div>
    </div>
  </template>
  
  <script setup>
  import { ref } from 'vue';
  import { useRouter } from 'vue-router';
  import axios from 'axios';
  import { useUserStore } from '../store/UserStore';

  const router = useRouter();
  const user_account = ref('');
  const password = ref('');
  const userStore = useUserStore();

  const login = async () => {
    if (!user_account.value) {
      alert('请输入账号');
      return;
    }
    if (!password.value) {
      alert('请输入密码');
      return;
    }
    try {
      const data = {
        user_account: user_account.value,
        password: password.value
      };
      const response = await axios.post('http://localhost:3000/api/user/login', data);
      if (response.data.message === '登录成功') {
        alert('登录成功');
        // 假设响应中包含用户信息和 JWT 令牌
        const userData = response.data.user;
        const token = response.data.token;
        userStore.login(userData, token);
        router.push('/home');
      } else {
        alert(response.data.message);
      }
    } catch (error) {
      console.error('登录出错:', error);
      alert('登录失败，请检查您的用户名或密码');
    }
  };
  </script>
  
  <style scoped>
  .login-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    margin-top: 100px;
  }
  
  input {
    margin: 10px 0;
    padding: 10px;
    width: 200px;
  }
  
  .login-button {
    margin-top: 20px;
    padding: 10px 20px;
    background-color: #007bff;
    color: white;
    border: none;
    border-radius: 5px;
    cursor: pointer;
  }
  
  .register-link {
    margin-top: 10px;
    text-align: right;
  }
  </style>